﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Globalization;

namespace OBNEPGGrabber
{
    static class M3UGenerator
    {
        private static IStatusUpdate m_IUpdate = null;
        private static string m_strFile = null;

        // Generate a channel list .m3u file from a channel list
        public static void Generate(DirectoryInfo diFolder, ref List<Channel> lstChannel, IStatusUpdate IUpdate)
        {
            try
            {
                m_IUpdate = IUpdate;
                m_strFile = diFolder.ToString() + "\\OBN.m3u";
                Regex rx = new Regex(@"\\[uU]([0-9A-Fa-f]{4})");

                TextWriter tw = new StreamWriter(m_strFile, false, Encoding.UTF8);
                tw.WriteLine("#EXTM3U");

                int iChannelNum = 1;
                bool bHD = false;

                foreach (Channel ch in lstChannel)
                {
                    if (ch.SDURL != null || ch.HDURL != null)
                    {
                        bHD = ch.HDURL != null;
                        ch.FriendlyName = rx.Replace(ch.FriendlyName, match => ((char)Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString());
                        ch.FriendlyName = ch.FriendlyName + (bHD && !ch.FriendlyName.EndsWith("HD") ? " HD" : "");
                        ch.FriendlyName = ch.FriendlyName.Replace("&", "&amp;");
                        //tw.WriteLine("#EXTINF:{0},{1}", iChannelNum.ToString(), ch.FriendlyName);
                        tw.WriteLine("#EXTINF:{0}, {1}", ch.ChannelNo.ToString(), ch.FriendlyName);
                        // So, HERE the SD channels are filtered out!!
                        if (bHD)
                        {
                            tw.WriteLine(ch.HDURL.ToString().Replace("//", "//@"));
                        }
                        else
                        {
                            tw.WriteLine(ch.SDURL.ToString().Replace("//", "//@"));
                        }
                        iChannelNum++;
                        tw.WriteLine("");
                    }
                }
                tw.Close();
            }
            catch (Exception)
            {
                m_IUpdate.UpdateStatus("Error generating channel .m3u file", true);
            }
        }
    }
}
